import axios from 'axios'

function getToken(){

}

function setToken(token){

}

function getRefreshToken(){

}
let promise ;
async function refreshToken(){
    if(promise){
        return promise;
    }
    promise=new Promise(async (resolve,reject)=>{
        console.log('刷新token');
        const reps = await requests.get('refresh_token',{
            headers:{
                Authorization: `Bearer ${getRefreshToken()}`
            },
            __isRefreshToken:true
        })
        resolve(reps.code===0) ;
    });
    promise.finally(()=>{
        promise =null;
    })
    return promise;
}

function isRefreshToken(config){
   return !!config.__isRefreshToken;
}

// 创建 axios 实例
const instance = axios.create({
    baseURL: 'http://baidu.com',
    headers: {
        Authorization: `Bearer ${getToken()}`
    }
})

instance.interceptors.response.use(async (res) => {
    
    if(res.headers.Authorization){
        const token = res.headers.Authorization.replace('Bearer ','');
        setToken(token);
        instance.defaults.headers.Authorization = `Bearer ${token}`
    }
    if(res.headers.refreshToken){
        const refreshToken=res.headers.refreshToken.replace('Bearer ','');
        setRefreshToken(refreshToken);
    }
    if(res.data.code===401 && !isRefreshToken(res.config)){
        // 刷新token
        const isSuccess = await refreshToken();
        if(isSuccess){
            // 有新的token后，重新请求
            console.log('重新请求');
            res.config.headers.Authorization= `Bearer ${getToken()}`
            const resp= await instance.requests(res.config);
            return resp
        }else{
            console.log("刷新token失败，跳转登录页")
        }
    }
    return res.data
})

export default instance;